public class Sulotion {

    public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder();//创建一个字符串
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();
    }

    private void tree2strChild(TreeNode root,StringBuilder stringBuilder){
        if(root == null){
            return;
        }

        stringBuilder.append(root.val);

        //完成左树的部分
        if(root.left != null){
            stringBuilder.append("(");
            tree2strChild(root.left,stringBuilder);
            stringBuilder.append(")");
        }else{
            if(root.right == null){
                return;

            }else{
                stringBuilder.append("()");
            }
        }

        //一定是递归完此时根节点的左树，才去递归右树
        //完成右树的部分
        if(root.right != null){
            stringBuilder.append("(");
            tree2strChild(root.right,stringBuilder);
            stringBuilder.append(")");
        }else{
            return;
        }
    }
}

